﻿<template>
  <div class="container" style="width:99%;margin-top:-25px;">
    <!-- 查询条件 -->
    <div class="query-box">
      <el-form :model="queryBox" status-icon ref="queryBox">
        <el-row>
          <el-col :span="4">
            <el-form-item label prop="code">
              <el-input v-model="queryBox.contactName" placeholder="联系人">
                <template slot="prepend">联系人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">大区经理</div>
              <el-input v-model="queryBox.belongToName" placeholder="大区经理">
              </el-input>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="depart-box">
              <div class="slect-title">跟进时间</div>
              <el-date-picker
                v-model="trackingDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div class="from-btns">
        <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button
          :label="$t('action.search')"
          perms="true"
          type="primary"
          @click="get_subcentersearch"
        />
      </div>
    </div>
    <div class="fr" style="margin-bottom:20px">
      <kt-button
        label="新增跟进"
        type="primary"
        perms="mycustomer:schoolTracking:addTracking"
        @click="handleNewADD"
      ></kt-button>
    </div>
    <!--表格内容栏-->
    <Crm-table
      class="table-width"
      :showBatchDelete="false"
      width="400"
      perms="true"
      :data="pageResult"
      :columns="columns"
      :loading="loading"
      @findPage="findPage"
      @handleFollow="handleFollow"
    ></Crm-table>
    <!-- 跟进 -->
    <el-dialog
      title="新增跟进"
      width="70%"
      :visible.sync="addFollow"
      :close-on-click-modal="false"
    >
      <div class="second-contain-box ma school-pop school-pop-t">
        <el-row>
          <el-col :span="6">
            <el-col :span="8">
              <i><em style="color:red">*</em> 联系人：</i>
            </el-col>
            <el-col :span="13">
              <el-input
                placeholder="请输入内容"
                v-model="saveData.contactName"
              ></el-input>
            </el-col>
          </el-col>
          <el-col :span="6">
            <el-col :span="8">
              <i><em style="color:red">*</em> 联系电话：</i>
            </el-col>
            <el-col :span="14">
              <el-input
                placeholder="请输入内容"
                type="phone"
                v-model="saveData.phone"
              ></el-input>
            </el-col>
          </el-col>
          <el-col :span="5">
            <el-col :span="9">
              <i>沟通形式：</i>
            </el-col>
            <el-col :span="12">
              <el-select
                style="width:100%"
                v-model="saveData.communicationType"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in student_communication_type"
                  :key="item.value"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-col>
          </el-col>
          <el-col :span="7">
            <el-col :span="8">
              <i>关联学校：</i>
            </el-col>
            <el-col :span="16">
              <el-input
                placeholder="请输入内容"
                type="phone"
                v-model="saveData.relatedSchool"
              ></el-input>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-col :span="4">
              <i>联系人单位：</i>
            </el-col>
            <el-col :span="7">
              <el-select
                style="width:100%;margin-left:-8px"
                v-model="saveData.company"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in school_track_type_options"
                  :key="item.value"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-input
              style="width:100%;"
              placeholder="单位详情"
              v-model="saveData.companyDetail"
            ></el-input>
            </el-col>
          </el-col>
          <el-col :span="5">
            <el-col :span="9">
              <i>跟进人：</i>
            </el-col>
            <el-col :span="12"   style="margin-top:12px;">
              {{ saveData.belongToName }}
            </el-col>
          </el-col>
          <el-col :span="7">
            <el-col :span="8">
              <i>跟进时间：</i>
            </el-col>
            <el-col :span="16">
              <el-date-picker
                style="width:100%"
                v-model="saveData.trackingDate"
                type="datetime"
                placeholder="选择日期时间"
                :default-time="mytime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </el-col>
          </el-col>
          
        </el-row>
        <el-row>
          
          <el-col :span="2">
            <i><em style="color:red">*</em> 情况描述：</i>
          </el-col>
          <el-col :span="22">
            <el-input
              style="width:100%;"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="saveData.communicationContent"
            ></el-input>
          </el-col>
            
        </el-row>
      </div>
      <kt-button
        class="stu-btn"
        :label="$t('action.save')"
        style='margin-top: 20px;'
        perms="true"
        size="medium"
        type="primary"
        @click="handleSave()"
      />
    </el-dialog>
  </div>
</template>
<script>
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import CustomerOwnership from "@/components/CustomerOwnership";
import { CodeToText } from "element-china-area-data";
import axios from "axios";
import Cookies from "js-cookie";
import { isMobile } from "@/utils/validate";
export default {
  name: "Student",
  components: {
    CrmTable,
    KtButton,
    CrmSwitch
  },
  data() {
    return {
      size: "small",
      filters: {
        name: ""
      },
      userName: "",
      // 查询条件
      queryBox: {
        contactName: "",
        belongToName: "",
        trackingDateStart: "",
        trackingDateEnd: ""
      },
      trackingDateArr: [], //跟进时间数组
      student_data_from_options: [],
      student_type_options: [],
      student_progress_options: [],

      student_level_cache_options: [],
      school_track_type_options:[],
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "contactName", label: "联系人", minWidth: 100 },
        { prop: "phone", label: "联系电话", minWidth: 80 },
        { prop: "communicationType", label: "沟通形式", minWidth: 100 },
        { prop: "companys", label: "联系人单位", minWidth: 100 },
        { prop: "school", label: "关联学校", minWidth: 100 },
        { prop: "communicationContent", label: "情况描述", minWidth: 200 },
        { prop: "belongToName", label: "跟进人", minWidth: 100 },
        // { prop: "createDate", label: "创建时间", minWidth: 140 },
        { prop: "trackingDate", label: "跟进时间", minWidth: 140 }
      ],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},

      operation: true, // true:新增, false:编辑
      selectionsLength: "",
      trackingDate: "",
      deptId: Cookies.get("threeLevelDeptId"),
      loading: false, // 加载标识
      saveData: {
        belongToId: Cookies.get("userId"),
        belongToName:Cookies.get("realName"),
        trackingDate:'',
        communicationType:''
      },
      // 限制跟进时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      trackingPeople: Cookies.get("realName"),
      addFollow: false,
      pageRequest2: {
        pageNum: 1,
        pageSize: 10
      },
      student_communication_type:[],
      mytime: "",
    };
  },

  methods: {
    // 客户类型
    get_student_type() {
      this.student_type_options = JSON.parse(
        localStorage.getItem("schoolType")
      );
    },

    // 客户来源
    get_student_data_from() {
      this.student_data_from_options = JSON.parse(
        localStorage.getItem("schoolSource")
      );
    },

    // 客户进展
    get_student_progress() {
      this.student_progress_options = JSON.parse(
        localStorage.getItem("schoolProgress")
      );
    },

    // 学段
    get_level_cache() {
      this.student_level_cache_options = JSON.parse(
        localStorage.getItem("schoolSection")
      );
    },

    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
      }

      if (this.trackingDate.length > 0) {
        this.queryBox.trackingDateStart = this.trackingDate[0];
        this.queryBox.trackingDateEnd = this.trackingDate[1];
      }

      this.pageRequest = Object.assign({}, this.pageRequest, this.queryBox);

      this.$api.school
        .queryTrackList(this.pageRequest)
        .then(res => {
          if (res.result == 1) {
            let content = { content: res.trackLists, totalSize: res.total };
            this.pageResult = content;
            this.pageResult.content.forEach(item => {
              // 单位拼装
              item.companys=(item.company==null?'':item.company+item.companyDetail==null?'':item.companyDetail)
              //转换地区
              if (
                (item.province == null && item.city == null) ||
                (item.province == "null" && item.city == "null")
              ) {
                item.diqu = "";
              } else {
                item.diqu =
                  CodeToText[item.province] +
                  CodeToText[item.city] +
                  CodeToText[item.area];
              }

              //转换来源
              this.student_data_from_options.forEach(type_item => {
                if (type_item.key == item.dataFrom) {
                  item.laiyuan = type_item.value;
                }
              });
              //转换客户类型
              this.student_type_options.forEach(type_item => {
                if (type_item.key == item.type) {
                  item.leixing = type_item.value;
                }
              });

              //转换客户进展
              this.student_progress_options.forEach(type_item => {
                if (type_item.key == item.progress) {
                  item.jinzhan = type_item.value;
                }
              });
              // 沟通形式
              this.student_communication_type.forEach(item_t => {
                if (item_t.key == item.communicationType) {
                  item.communicationType = item_t.value;
                }
              });
              // 转换学段
              if (item.schoolSection != "" && item.schoolSection != null) {
                let schoolSection = item.schoolSection.split(",");
                let sectionStr = "";
                schoolSection.forEach((schoolSection, index) => {
                  this.student_level_cache_options.forEach(level_cache => {
                    if (level_cache.key == schoolSection) {
                      sectionStr = sectionStr + level_cache.value + ",";
                    }
                  });
                });
                item.xueDuan = sectionStr.substring(
                  0,
                  sectionStr.lastIndexOf(",")
                );
              }
            });
          } else {
          }
          this.loading = false;
        })
        .then(data != null ? data.callback : "");
    },

    //查询接口
    get_subcentersearch() {
      this.loading = true;
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },

    // 新增跟进
    handleNewADD: function() {
      this.pageRequest2.pageNum = "1";

      this.addFollow = true;

      this.saveData.communicationType = "1";

      this.findPage(null);
      this.get_dataTime()
      this.get_school_traclk_type()
    },

    // 重置
    reset(queryBox) {
      this.$refs.queryBox.resetFields();
      this.queryBox.contactName = "";
      this.queryBox.belongToName = "";
      this.queryBox.trackingDateStart = "";
      this.queryBox.trackingDateEnd = "";
      this.trackingDate=[]
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },

    // 查看客户档案
    handleFollow(params) {
      this.dataForm = Object.assign({}, params.row);
      this.$router.push({
        path: "/Follow/SchoolFollow",
        query: {
          id: this.dataForm.id,
          name: params.row.name
        }
      });
    },

    selectionChange: function(params) {
      let selectionsLength = params.selections.length;
      this.selectionsLength = selectionsLength;
      console.log(selectionsLength);
    },
    // 跟进人
    querySearchAsync2(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      this.$api.dropdown.users({ userType: 3 }).then(res => {
        for (let i of res.userInfoList) {
          i.value = i.realName; //将想要展示的数据作为value
        }
        restaurants = res.userInfoList;
        results = queryString
          ? restaurants.filter(this.createFilter2(queryString))
          : restaurants;
        callback(results);
      });
    },
    createFilter2(queryString) {
      return restaurant => {
        return (
          restaurant.realName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect2(item) {
      this.queryBox.belongToId = item.id;
    },
    // 沟通形式
    get_contractType() {
      this.$api.school.school_communication_type().then(res => {
        this.student_communication_type = res.keyValueList;
      });
      this.saveData.belongToName = this.trackingPeople;
    },
    // 联系人单位
    get_school_traclk_type(){
      this.$api.dropdown.schoolTrackType().then(res => {
        this.school_track_type_options = res.keyValueList;
      });
    },
    handleSave(){
      if(this.saveData.contactName==''||this.saveData.contactName==undefined){
        this.$message({
            message:'联系人不能为空！',
            type: "error"
          });
        return false
      }
      if(!isMobile(this.saveData.phone)){
        this.$message({
            message:'联系电话有误！',
            type: "error"
          });
        return false
      }
      this.$api.school.addTrack({userId:'',schoolTrackingInfo:this.saveData}).then(res => {
        if (res.result != 1) {
          this.$message({
            message: res.msg,
            type: "error"
          });
        } else {
          this.$message({
            message: res.msg,
            type: "success"
          });
          this.addFollow = false;
          this.saveData.communicationContent = "";
          this.saveData.communicationType = "";
          this.saveData.company = "";
          this.saveData.companyDetail = "";
          this.saveData.contactName = "";
          this.saveData.phone = "";
          this.saveData.relatedSchool = "";
          this.saveData.trackingDate = "";
          this.findPage(null);
        }
      });
    },
    get_dataTime() {
      let dateTime = new Date();
      this.saveData.trackingDate = this.dateFormat(dateTime);
      let mytime = dateTime.toLocaleTimeString("chinese", { hour12: false }); //获取当前时间
      this.mytime = mytime;
    },
     // 获取时间
    dateFormat: function(time) {
      var date = new Date(time);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
  },
  mounted() {
    this.get_student_type();
    this.get_student_data_from();
    this.get_student_progress();
    this.get_level_cache();
    this.get_contractType();
  }
};
</script>
<style>
@import url("../../assets/queryBox.css");
</style>
<style lang="scss" scope>
.add-btns .el-button:nth-child(1) {
  margin-right: 10px;
}
.second-contain-box {
  margin: 0 auto;
  .el-col {
    text-align: left;
    margin: 4px 0;
  }
  .el-row {
    margin: 0 0 !important;
  }
  .el-col i {
    font-style: normal;
    display: inline-block;
    margin-top: 10%;
  }
  .el-input--suffix .el-input__inner{
    margin-right: 0px;
  }
  
}

</style>
<style lang="scss">
.school-pop-t{
  .el-input--suffix .el-input__inner{
    padding-right: 0px !important
  }
}
</style>
